﻿using Qy.Core;
using Qy.Scenario;
using Qy.Web.Authorize.Common;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;

namespace Qy.Web.Authorize;


public class LoginUserInfoMethods: ILoginUserInfoMethods
{
    private readonly UserService _adminUserService;
    private readonly UserGroupService _userGroupService;
    public LoginUserInfoMethods(UserService adminUserService, UserGroupService userGroupService)
    {
        _adminUserService = adminUserService;
        _userGroupService = userGroupService;
    }

    /// <summary>
    /// 登录用户ID
    /// </summary>
    /// <returns></returns>
    public int LoginUserId()
    {
        return App.HttpContext.GetUId();
    }

    /// <summary>
    /// 登录用户名
    /// </summary>
    /// <returns></returns>
    public string LoginUserName()
    {
        return App.HttpContext.GetName();
    }

    public int LoginGroupId()
    {
        return App.HttpContext.GetGId();
    }

    public async Task<ILoginUserInfo> LoginUserInfoAsync()
    {
        int userId = LoginUserId();
        if (userId < 1) return null;
        try
        {
            ViewUser user = await _adminUserService.GetCacheAsync(userId);
            UserGroup userGroup = await _userGroupService.GetOne(user.GroupId);
            LoginUserInfo loginUserInfo = new()
            {
                UserId = userId,
                GroupId = user.GroupId,
                DeptId = user.DeptId,
                PostId = user.PostId,
                PostName = user.PostName,
                PostCode = user.PostCode,
                DeptName = user.DeptName,
                UserName = user.UserName,
                NickName = user.NickName,
                Status = user.Status,
                Avatar = user.Avatar,
                Phone = user.Phone,
                Sex = user.Sex,
                GroupName = userGroup.GroupName,
                SystemRole = JsonSerializer.Deserialize<List<int>>(userGroup.SystemRole)
            };
            return loginUserInfo;
        }
        catch
        {
            return null;
        }

    }

}
